package com.innovation.config;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.innovation.config.GlobalConfig.DBConfig;


public class SqlMapperConfig {
	private static final String RES_MAPPER_FILE = "com/innovation/config/maps/ResMapperConfig.xml"; //资源库配置文件
	private static final String DATA_MAPPER_FILE = "com/innovation/data/maps/DataMapperConfig.xml"; //玩家数据配置文件
	
	private static SqlSessionFactory resSessionFactory = null;
	private static SqlSessionFactory dataSessionFactory = null; //单库
//	//分库时使用
//	private static Map<Integer, SqlSessionFactory> dataSessionFactoryMap = new HashMap<Integer, SqlSessionFactory>();
	
	/**
	 * 初始化资源库数据连接
	 * @throws IOException
	 */
	public static void initResSessionFactory() throws IOException{
		Reader reader = Resources.getResourceAsReader(RES_MAPPER_FILE);
		DBConfig dbConfig = GlobalConfig.RESDB;
		Properties properties = new Properties();
		properties.put("driver", dbConfig.driver);
		properties.put("url", dbConfig.url);
		properties.put("username", dbConfig.userName);
		properties.put("password", dbConfig.password);
		resSessionFactory = new SqlSessionFactoryBuilder().build(reader,properties); 
		reader.close();
	}
	
	public static void initDataSessionFactory(int zoneId) throws IOException{
		Reader reader = Resources.getResourceAsReader(DATA_MAPPER_FILE);
		Map<Integer, DBConfig> dbMap = GlobalConfig.getZoneConfig(zoneId).dbMap;
		DBConfig dbConfig = dbMap.values().iterator().next();
		Properties properties = new Properties();
		properties.put("driver", dbConfig.driver);
		properties.put("url", dbConfig.url);
		properties.put("username", dbConfig.userName);
		properties.put("password", dbConfig.password);
		dataSessionFactory = new SqlSessionFactoryBuilder().build(reader,properties);
		
//分库时使用
//		for(Entry<Integer, DBConfig> entry : dbMap.entrySet()){
//			DBConfig dbConfig = entry.getValue();
//			Properties properties = new Properties();
//			properties.put("driver", dbConfig.driver);
//			properties.put("url", dbConfig.url);
//			properties.put("username", dbConfig.userName);
//			properties.put("password", dbConfig.password);
//			dataSessionFactoryMap.put(dbConfig.id, new SqlSessionFactoryBuilder().build(reader,properties)); 
//		}
		reader.close();
	}
	
	public static SqlSessionFactory getResSessionFactory(){
		return resSessionFactory;
	}
	
	public static SqlSessionFactory getDataSessionFactory(){
		return dataSessionFactory;
	}
}

